package main

import (
	"fitness/go-admin/internal/config"
	"fitness/go-admin/internal/handler"
	"fitness/go-admin/internal/middleware"
	"fitness/go-admin/internal/repository"
	"fitness/go-admin/internal/service"
	"fitness/go-admin/pkg/cache"
	"fitness/go-admin/pkg/database"
	"fitness/go-admin/pkg/logger"
	"fitness/go-admin/pkg/utils"
	"fmt"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg := config.Load()

	// 设置全局配置变量
	config.GlobalConfig = cfg

	// 初始化日志系统
	if err := logger.InitLogger(cfg.Log.Path, cfg.Log.Level); err != nil {
		log.Fatalf("日志系统初始化失败: %v", err)
	}
	defer logger.Sync()
	logger.Info("日志系统初始化成功")

	// 初始化JWT配置
	utils.InitJWT(cfg.JWT.AccessSecret, cfg.JWT.RefreshSecret, cfg.JWT.AccessExpire, cfg.JWT.RefreshExpire)

	// 初始化Redis
	if err := cache.InitRedis(cfg.Redis.Host, cfg.Redis.Port, cfg.Redis.Password, cfg.Redis.DB); err != nil {
		log.Printf("Redis连接失败（非必需）: %v", err)
	} else {
		log.Println("Redis连接成功")
	}

	// 初始化数据库
	db := database.InitMySQL(cfg)

	// 初始化 Repository 层
	userRepo := repository.NewUserRepository(db)
	roleRepo := repository.NewRoleRepository(db)
	permissionRepo := repository.NewPermissionRepository(db)
	memberRepo := repository.NewMemberRepository(db)
	courseRepo := repository.NewCourseRepository(db)
	coachRepo := repository.NewCoachRepository(db)
	planRepo := repository.NewPlanRepository(db)
	bookingRepo := repository.NewBookingRepository(db)
	// 会员卡相关
	cardTypeRepo := repository.NewCardTypeRepository(db)
	cardRepo := repository.NewMembershipCardRepository(db)
	rechargeRepo := repository.NewRechargeRecordRepository(db)
	consumptionRepo := repository.NewConsumptionRecordRepository(db)
	balanceLogRepo := repository.NewBalanceLogRepository(db)
	// 统计相关
	statsRepo := repository.NewStatisticsRepository(db)
	// 文件相关
	fileRepo := repository.NewFileRepository(db)
	// 评价反馈相关
	reviewRepo := repository.NewReviewRepository(db)
	// 签到打卡相关
	checkinRepo := repository.NewCheckinRepository(db)
	// 通知推送相关
	notificationRepo := repository.NewNotificationRepository(db)
	// 菜单相关
	menuRepo := repository.NewMenuRepository(db)
	// 操作日志相关
	operationLogRepo := repository.NewOperationLogRepository(db)
	// 字典管理相关
	dictTypeRepo := repository.NewDictRepository(db)
	// 客服聊天相关
	chatRepo := repository.NewChatRepository(db)

	// 初始化 Service 层
	authService := service.NewAuthService(userRepo, roleRepo)
	userService := service.NewUserService(userRepo, roleRepo)
	permissionService := service.NewPermissionService(permissionRepo, roleRepo)
	memberService := service.NewMemberService(memberRepo)
	courseService := service.NewCourseService(courseRepo)
	coachService := service.NewCoachService(coachRepo)
	planService := service.NewPlanService(planRepo)
	bookingService := service.NewBookingService(bookingRepo, courseRepo, memberRepo, userRepo)
	// 会员卡服务
	cardService := service.NewMembershipCardService(db, cardTypeRepo, cardRepo, rechargeRepo, consumptionRepo, balanceLogRepo, memberRepo)
	// 统计服务
	statsService := service.NewStatisticsService(statsRepo)
	// 文件服务
	fileService := service.NewFileService(fileRepo, db)
	// 评价反馈服务
	reviewService := service.NewReviewService(reviewRepo)
	// 签到打卡服务
	checkinService := service.NewCheckinService(checkinRepo)
	// 通知推送服务
	notificationService := service.NewNotificationService(notificationRepo)
	// 菜单服务
	menuService := service.NewMenuService(menuRepo)
	// 操作日志服务
	operationLogService := service.NewOperationLogService(operationLogRepo)
	// 字典管理服务
	dictService := service.NewDictService(dictTypeRepo)
	// 客服聊天服务
	chatService := service.NewChatService(chatRepo, userRepo)

	// 初始化 Handler 层
	authHandler := handler.NewAuthHandler(authService)
	userHandler := handler.NewUserHandler(userService)
	permissionHandler := handler.NewPermissionHandler(permissionService)
	memberHandler := handler.NewMemberHandler(memberService)
	courseHandler := handler.NewCourseHandler(courseService)
	coachHandler := handler.NewCoachHandler(coachService)
	planHandler := handler.NewPlanHandler(planService)
	bookingHandler := handler.NewBookingHandler(bookingService)
	// 会员卡处理器
	cardHandler := handler.NewMembershipCardHandler(cardService)
	// 统计处理器
	statsHandler := handler.NewStatisticsHandler(statsService)
	// 文件处理器
	fileHandler := handler.NewFileHandler(fileService)
	// 评价反馈处理器
	reviewHandler := handler.NewReviewHandler(reviewService)
	// 签到打卡处理器
	checkinHandler := handler.NewCheckinHandler(checkinService)
	// 通知推送处理器
	notificationHandler := handler.NewNotificationHandler(notificationService)
	// 菜单处理器
	menuHandler := handler.NewMenuHandler(menuService)
	// 操作日志处理器
	operationLogHandler := handler.NewOperationLogHandler(operationLogService)
	// 字典管理处理器
	dictHandler := handler.NewDictHandler(dictService)
	// 快捷回复服务
	quickReplyRepo := repository.NewQuickReplyRepository(db)
	quickReplyService := service.NewQuickReplyService(quickReplyRepo)
	// 客服聊天处理器
	chatHandler := handler.NewChatHandler(chatService, fileService)
	// 快捷回复处理器
	quickReplyHandler := handler.NewQuickReplyHandler(quickReplyService)
	// 客服统计服务
	chatStatsRepo := repository.NewChatStatisticsRepository(db)
	chatStatsService := service.NewChatStatisticsService(chatStatsRepo, userRepo)
	chatStatsHandler := handler.NewChatStatisticsHandler(chatStatsService)
	// 敏感词服务
	sensitiveWordRepo := repository.NewSensitiveWordRepository(db)
	sensitiveWordService := service.NewSensitiveWordService(sensitiveWordRepo)
	sensitiveWordHandler := handler.NewSensitiveWordHandler(sensitiveWordService)
	// 将敏感词服务注入到聊天服务
	chatService.SetSensitiveWordService(sensitiveWordService)
	// 表情服务
	emojiRepo := repository.NewEmojiRepository(db)
	emojiService := service.NewEmojiService(emojiRepo)
	emojiHandler := handler.NewEmojiHandler(emojiService)

	// 设置 Gin 模式
	gin.SetMode(cfg.Server.Mode)

	// 创建路由
	r := gin.Default()

	// 全局中间件
	r.Use(middleware.RequestID())
	r.Use(middleware.CORS(cfg))
	r.Use(middleware.Logger())
	r.Use(middleware.OperationLog(userRepo, operationLogService))
	r.Use(middleware.QueryMonitor()) // 查询性能监控

	// API 路由组
	api := r.Group("/api/v1")
	{
		// 认证相关接口（不需要认证）
		auth := api.Group("/auth")
		{
			auth.POST("/register", middleware.RegisterRateLimit(), authHandler.Register)
			auth.POST("/login", middleware.LoginRateLimit(), authHandler.Login)
			auth.POST("/refresh-token", middleware.RefreshTokenRateLimit(), authHandler.RefreshToken)
			auth.GET("/userinfo", middleware.Auth(), authHandler.GetUserInfo)
			auth.POST("/change-password", middleware.Auth(), authHandler.ChangePassword)
			auth.PUT("/profile", middleware.Auth(), authHandler.UpdateProfile)
			auth.POST("/logout", middleware.Auth(), authHandler.Logout)
		}

		// 会员管理
		members := api.Group("/members")
		{
			members.GET("", memberHandler.List)
			members.GET("/:id", memberHandler.Get)
			members.POST("", memberHandler.Create)
			members.PUT("/:id", memberHandler.Update)
			members.DELETE("/:id", memberHandler.Delete)
		}

		// 课程预约
		courses := api.Group("/courses")
		{
			courses.GET("", courseHandler.List)
			courses.GET("/:id", courseHandler.Get)
			courses.POST("", courseHandler.Create)
			courses.PUT("/:id", courseHandler.Update)
			courses.DELETE("/:id", courseHandler.Delete)
		}

		// 教练管理
		coaches := api.Group("/coaches")
		{
			coaches.GET("", coachHandler.List)
			coaches.GET("/:id", coachHandler.Get)
			coaches.POST("", coachHandler.Create)
			coaches.PUT("/:id", coachHandler.Update)
			coaches.DELETE("/:id", coachHandler.Delete)
		}

		// 健身计划
		plans := api.Group("/plans")
		{
			plans.GET("", planHandler.List)
			plans.GET("/:id", planHandler.Get)
			plans.POST("", planHandler.Create)
			plans.PUT("/:id", planHandler.Update)
			plans.DELETE("/:id", planHandler.Delete)
		}

		// 用户管理 (需要管理员权限)
		users := api.Group("/users")
		users.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			users.GET("", userHandler.List)                    // 获取用户列表
			users.GET("/:id", userHandler.Get)                 // 获取用户详情
			users.PUT("/:id", userHandler.Update)              // 更新用户信息
			users.PUT("/:id/status", userHandler.UpdateStatus) // 启用/禁用用户
			users.PUT("/:id/role", userHandler.UpdateRole)     // 修改用户角色
		}

		// 权限管理 (需要管理员权限)
		permissions := api.Group("/permissions")
		permissions.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			permissions.GET("", permissionHandler.List)    // 获取权限列表
			permissions.POST("", permissionHandler.Create) // 创建权限
		}

		// 角色权限管理 (需要管理员权限)
		roles := api.Group("/roles")
		roles.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			roles.GET("/:id/permissions", permissionHandler.GetRolePermissions)                    // 获取角色权限列表
			roles.POST("/:id/permissions", permissionHandler.AssignPermissions)                    // 分配权限
			roles.DELETE("/:roleId/permissions/:permissionId", permissionHandler.RemovePermission) // 移除权限
		}

		// 菜单管理 (需要管理员权限)
		menus := api.Group("/menus")
		menus.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			menus.GET("", menuHandler.List)                    // 获取菜单列表
			menus.GET("/:id", menuHandler.Get)                 // 获取菜单详情
			menus.POST("", menuHandler.Create)                 // 创建菜单
			menus.PUT("/:id", menuHandler.Update)              // 更新菜单
			menus.DELETE("/:id", menuHandler.Delete)           // 删除菜单
			menus.PUT("/:id/status", menuHandler.UpdateStatus) // 更新菜单状态
		}

		// 课程预约 (需要认证)
		bookings := api.Group("/bookings")
		bookings.Use(middleware.Auth())
		{
			bookings.POST("", bookingHandler.Create)              // 创建预约
			bookings.GET("/my", bookingHandler.MyBookings)        // 我的预约列表
			bookings.GET("/:id", bookingHandler.Get)              // 预约详情
			bookings.DELETE("/:id", bookingHandler.Cancel)        // 取消预约
			bookings.POST("/:id/checkin", bookingHandler.CheckIn) // 签到
		}

		// 课程预约列表（按课程查询）
		api.GET("/courses/:id/bookings", middleware.Auth(), bookingHandler.ListByCourse)

		// 管理员预约管理 (需要管理员权限)
		adminBookings := api.Group("/admin/bookings")
		adminBookings.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			adminBookings.GET("", bookingHandler.AdminList)          // 查看所有预约
			adminBookings.DELETE("/:id", bookingHandler.AdminCancel) // 取消任何预约
		}

		// 会员卡类型管理 (需要管理员权限)
		cardTypes := api.Group("/cards/types")
		{
			cardTypes.GET("", cardHandler.ListCardTypes)             // 获取卡类型列表
			cardTypes.GET("/active", cardHandler.GetActiveCardTypes) // 获取启用的卡类型
			cardTypes.GET("/:id", cardHandler.GetCardType)           // 获取卡类型详情
			// 以下需要管理员权限
			cardTypes.POST("", middleware.Auth(), middleware.AdminAuth(userRepo), cardHandler.CreateCardType)       // 创建卡类型
			cardTypes.PUT("/:id", middleware.Auth(), middleware.AdminAuth(userRepo), cardHandler.UpdateCardType)    // 更新卡类型
			cardTypes.DELETE("/:id", middleware.Auth(), middleware.AdminAuth(userRepo), cardHandler.DeleteCardType) // 删除卡类型
		}

		// 会员卡管理 (需要认证)
		cards := api.Group("/cards")
		cards.Use(middleware.Auth())
		{
			cards.POST("", cardHandler.CreateCard)                            // 开卡
			cards.GET("", cardHandler.ListCards)                              // 获取会员卡列表
			cards.GET("/:id", cardHandler.GetCard)                            // 获取会员卡详情
			cards.POST("/:id/renew", cardHandler.RenewCard)                   // 续卡
			cards.PUT("/:id/freeze", cardHandler.FreezeCard)                  // 冻结/解冻卡
			cards.DELETE("/:id", cardHandler.CancelCard)                      // 注销卡
			cards.POST("/:id/recharge", cardHandler.Recharge)                 // 充值
			cards.POST("/:id/consume", cardHandler.Consume)                   // 消费
			cards.GET("/:id/balance", cardHandler.GetBalance)                 // 查询余额
			cards.GET("/:id/recharges", cardHandler.GetRechargeRecords)       // 充值记录
			cards.GET("/:id/consumptions", cardHandler.GetConsumptionRecords) // 消费记录
			cards.GET("/:id/balance-logs", cardHandler.GetBalanceLogs)        // 余额日志
			cards.GET("/:id/statistics", cardHandler.GetStatistics)           // 消费统计

			// 新增：获取当前用户的会员卡信息和个人交易记录
			cards.GET("/my", cardHandler.GetMyCard)                      // 获取我的会员卡信息
			cards.GET("/my/transactions", cardHandler.GetMyTransactions) // 获取我的交易记录
		}

		// 数据统计 (需要认证，部分需要管理员权限)
		stats := api.Group("/statistics")
		stats.Use(middleware.Auth())
		{
			// 综合统计
			stats.GET("/overview", statsHandler.GetOverview) // 数据概览
			stats.GET("/trends", statsHandler.GetTrends)     // 趋势对比

			// 会员统计
			stats.GET("/members/growth", statsHandler.GetMemberGrowth)             // 会员增长
			stats.GET("/members/distribution", statsHandler.GetMemberDistribution) // 会员分布

			// 课程统计
			stats.GET("/courses/ranking", statsHandler.GetCourseRanking)        // 课程排行
			stats.GET("/courses/bookings", statsHandler.GetCourseBookingTrends) // 预约趋势
			stats.GET("/courses/timeslots", statsHandler.GetTimeslotStats)      // 时段分析

			// 教练统计
			stats.GET("/coaches/workload", statsHandler.GetCoachWorkload) // 教练工作量
			stats.GET("/coaches/ranking", statsHandler.GetCoachRanking)   // 教练排行

			// 营收统计 (需要管理员权限)
			statsRevenue := stats.Group("/revenue")
			statsRevenue.Use(middleware.AdminAuth(userRepo))
			{
				statsRevenue.GET("/overview", statsHandler.GetRevenueOverview)     // 营收总览
				statsRevenue.GET("/trends", statsHandler.GetRevenueTrends)         // 营收趋势
				statsRevenue.GET("/consumption", statsHandler.GetConsumptionStats) // 消费统计
			}
		}

		// 文件上传模块 (需要认证)
		files := api.Group("/files")
		files.Use(middleware.Auth())
		{
			files.POST("/upload", fileHandler.UploadFile)
			files.GET("", fileHandler.GetFileList)
			files.GET("/:id", fileHandler.GetFileInfo)
			files.DELETE("/:id", fileHandler.DeleteFile)
			files.POST("/batch-delete", fileHandler.BatchDeleteFiles)
			files.GET("/statistics", fileHandler.GetFileStatistics)
		}

		// 训练照片模块
		trainingPhotos := api.Group("/training-photos")
		trainingPhotos.Use(middleware.Auth())
		{
			trainingPhotos.POST("", fileHandler.AddTrainingPhoto)
			trainingPhotos.GET("", fileHandler.GetTrainingPhotoList)
			trainingPhotos.GET("/:id", fileHandler.GetTrainingPhoto)
			trainingPhotos.DELETE("/:id", fileHandler.DeleteTrainingPhoto)
			trainingPhotos.GET("/timeline/:memberId", fileHandler.GetMemberPhotoTimeline)
			trainingPhotos.PUT("/:id/public", fileHandler.TogglePhotoPublic)
		}

		// 教练证书模块
		certificates := api.Group("/coach-certificates")
		certificates.Use(middleware.Auth())
		{
			certificates.POST("", fileHandler.AddCoachCertificate)
			certificates.GET("", fileHandler.GetCoachCertificateList)
			certificates.GET("/:id", fileHandler.GetCoachCertificate)
			certificates.DELETE("/:id", fileHandler.DeleteCoachCertificate)
			certificates.GET("/coach/:coachId", fileHandler.GetCoachCertificates)
			certificates.PUT("/:id/verify", middleware.AdminAuth(userRepo), fileHandler.VerifyCertificate)
		}

		// 评价反馈模块 (需要认证)
		reviews := api.Group("/reviews")
		reviews.Use(middleware.Auth())
		{
			// 课程评价
			reviews.POST("/courses", reviewHandler.CreateCourseReview)
			reviews.GET("/courses/:courseId", reviewHandler.GetCourseReviews)
			reviews.POST("/:id/helpful", reviewHandler.MarkReviewHelpful)
			reviews.DELETE("/:id/helpful", reviewHandler.UnmarkReviewHelpful)
			reviews.POST("/:id/reply/:type", reviewHandler.ReplyToReview)

			// 教练评分
			reviews.POST("/coaches", reviewHandler.CreateCoachRating)
			reviews.GET("/coaches/:coachId", reviewHandler.GetCoachRatings)
		}

		// 意见反馈模块
		feedbacks := api.Group("/feedbacks")
		feedbacks.Use(middleware.Auth())
		{
			feedbacks.POST("", reviewHandler.CreateFeedback)
			feedbacks.GET("", reviewHandler.GetAllFeedbacks)     // 获取所有反馈（管理员）
			feedbacks.GET("/my", reviewHandler.GetMyFeedbacks)   // 获取我的反馈
			feedbacks.PUT("/:id/handle", middleware.AdminAuth(userRepo), reviewHandler.HandleFeedback)
		}

		// 评价管理 (管理员功能)
		adminReviews := api.Group("/admin/reviews")
		adminReviews.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			adminReviews.PUT("/:id/audit", reviewHandler.AuditReview)
			adminReviews.PUT("/:id/featured", reviewHandler.FeatureReview)
			adminReviews.PUT("/:id/hide", reviewHandler.HideReview)
			adminReviews.GET("/reports", reviewHandler.GetReviewReports)
			adminReviews.PUT("/reports/:id/handle", reviewHandler.HandleReviewReport)
		}

		// 评价举报 (需要认证)
		reviewReports := api.Group("/reviews")
		reviewReports.Use(middleware.Auth())
		{
			reviewReports.POST("/report", reviewHandler.ReportReview)
		}

		// 签到打卡模块 (需要认证)
		checkins := api.Group("/checkins")
		checkins.Use(middleware.Auth())
		{
			checkins.POST("", checkinHandler.CreateCheckin)                     // 会员进馆签到
			checkins.POST("/checkout", checkinHandler.CreateCheckout)           // 会员离馆签退
			checkins.GET("/my", checkinHandler.GetMyCheckins)                   // 我的签到记录
			checkins.GET("/statistics", checkinHandler.GetCheckinStatistics)    // 签到统计概览
			checkins.GET("/validate-location", checkinHandler.ValidateLocation) // 验证地理位置
			checkins.GET("/validate-qrcode", checkinHandler.ValidateQRCode)     // 验证二维码
		}

		// 前台签到管理 (需要前台权限)
		staffCheckins := api.Group("/staff/checkins")
		staffCheckins.Use(middleware.Auth())
		{
			staffCheckins.GET("", checkinHandler.GetStaffCheckins)    // 前台查看签到列表
			staffCheckins.POST("", checkinHandler.CreateStaffCheckin) // 前台代会员签到
		}

		// 管理员签到管理 (需要管理员权限)
		adminCheckins := api.Group("/admin/checkins")
		adminCheckins.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			adminCheckins.GET("", checkinHandler.GetAdminCheckins)            // 管理员查看所有签到
			adminCheckins.GET("/analytics", checkinHandler.GetAdminAnalytics) // 签到数据统计分析
			adminCheckins.POST("/qrcode", checkinHandler.GenerateQRCode)      // 生成签到二维码
			adminCheckins.POST("/batch", checkinHandler.BatchCheckin)         // 批量补签/删除签到
		}

		// 通知推送模块 (需要认证)
		notifications := api.Group("/notifications")
		notifications.Use(middleware.Auth())
		{
			notifications.GET("", notificationHandler.GetNotifications)            // 获取通知列表
			notifications.GET("/unread-count", notificationHandler.GetUnreadCount) // 获取未读数量
			notifications.PUT("/:id/read", notificationHandler.MarkAsRead)         // 标记为已读
			notifications.PUT("/read-batch", notificationHandler.MarkBatchAsRead)  // 批量标记已读
			notifications.PUT("/read-all", notificationHandler.MarkAllAsRead)      // 全部标记已读
			notifications.DELETE("/:id", notificationHandler.DeleteNotification)   // 删除通知

			notifications.GET("/settings", notificationHandler.GetNotificationSettings)    // 获取通知设置
			notifications.PUT("/settings", notificationHandler.UpdateNotificationSettings) // 更新通知设置
		}

		// 系统公告模块 (需要认证)
		announcements := api.Group("/announcements")
		announcements.Use(middleware.Auth())
		{
			announcements.GET("", notificationHandler.GetAnnouncements)          // 获取公告列表
			announcements.GET("/:id", notificationHandler.GetAnnouncementDetail) // 获取公告详情

			// 管理员公告管理 (需要管理员权限)
			adminAnnouncements := announcements.Group("")
			adminAnnouncements.Use(middleware.AdminAuth(userRepo))
			{
				adminAnnouncements.POST("", notificationHandler.CreateAnnouncement)              // 创建公告
				adminAnnouncements.PUT("/:id", notificationHandler.UpdateAnnouncement)           // 更新公告
				adminAnnouncements.DELETE("/:id", notificationHandler.DeleteAnnouncement)        // 删除公告
				adminAnnouncements.POST("/:id/publish", notificationHandler.PublishAnnouncement) // 发布公告
			}
		}

		// 通知模板管理 (需要管理员权限)
		notificationTemplates := api.Group("/notifications/templates")
		notificationTemplates.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			notificationTemplates.GET("", notificationHandler.GetTemplates)          // 获取模板列表
			notificationTemplates.POST("", notificationHandler.CreateTemplate)       // 创建模板
			notificationTemplates.PUT("/:id", notificationHandler.UpdateTemplate)    // 更新模板
			notificationTemplates.DELETE("/:id", notificationHandler.DeleteTemplate) // 删除模板
		}

		// 操作日志管理 (需要管理员权限)
		operationLogs := api.Group("/operation-logs")
		operationLogs.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			operationLogs.GET("", operationLogHandler.List)                      // 获取操作日志列表
			operationLogs.GET("/:id", operationLogHandler.Get)                   // 获取操作日志详情
			operationLogs.DELETE("/:id", operationLogHandler.Delete)             // 删除操作日志
			operationLogs.POST("/batch-delete", operationLogHandler.BatchDelete) // 批量删除操作日志
		}

		// 字典管理 (需要管理员权限)
		dict := api.Group("/dict")
		dict.Use(middleware.Auth(), middleware.AdminAuth(userRepo))
		{
			// 字典类型管理
			types := dict.Group("/types")
			{
				types.POST("", dictHandler.CreateDictType)       // 创建字典类型
				types.GET("/:id", dictHandler.GetDictType)       // 获取字典类型详情
				types.GET("", dictHandler.ListDictTypes)         // 获取字典类型列表
				types.PUT("/:id", dictHandler.UpdateDictType)    // 更新字典类型
				types.DELETE("/:id", dictHandler.DeleteDictType) // 删除字典类型
			}

			// 字典数据管理
			data := dict.Group("/data")
			{
				data.POST("", dictHandler.CreateDictData)              // 创建字典数据
				data.GET("/:id", dictHandler.GetDictData)              // 获取字典数据详情
				data.GET("", dictHandler.ListDictData)                 // 获取字典数据列表
				data.GET("/type/:type", dictHandler.GetDataByDictType) // 根据字典类型获取数据
				data.PUT("/:id", dictHandler.UpdateDictData)           // 更新字典数据
				data.DELETE("/:id", dictHandler.DeleteDictData)        // 删除字典数据
				data.POST("/batch", dictHandler.BatchDeleteDictData)   // 批量删除字典数据
			}
		}

		// 客服聊天系统 (需要认证)
		chat := api.Group("/chat")
		chat.Use(middleware.Auth())
		{
			// WebSocket连接
			chat.GET("/ws", chatHandler.ConnectWebSocket) // WebSocket升级

			// 会话管理
			chat.POST("/sessions", chatHandler.CreateSession)          // 创建会话
			chat.GET("/sessions", chatHandler.GetSessions)             // 获取会话列表
			chat.GET("/sessions/:id", chatHandler.GetSession)          // 获取会话详情
			chat.POST("/sessions/:id/close", chatHandler.CloseSession) // 关闭会话

			// 消息管理
			chat.POST("/messages", chatHandler.SendMessage)              // 发送消息
			chat.GET("/messages", chatHandler.GetMessages)               // 获取消息列表
			chat.GET("/messages/search", chatHandler.SearchMessages)     // 搜索消息
			chat.POST("/messages/read", chatHandler.MarkMessagesAsRead)  // 标记已读
			chat.POST("/messages/:id/recall", chatHandler.RecallMessage) // 撤回消息
			chat.GET("/unread-count", chatHandler.GetUnreadCount)        // 获取未读数
			chat.POST("/typing", chatHandler.NotifyTyping)               // 正在输入通知
			chat.POST("/upload", chatHandler.UploadChatFile)             // 上传文件

			// 在线状态
			chat.GET("/online-status", chatHandler.GetOnlineStatus) // 获取在线状态

			// 客服端功能（需要管理员或教练权限）
			staff := chat.Group("/staff")
			{
				staff.GET("/waiting", chatHandler.GetWaitingSessions)                                         // 获取等待会话
				staff.POST("/sessions/:id/take", chatHandler.TakeSession)                                     // 客服接入会话
				staff.POST("/sessions/:id/assign", middleware.AdminAuth(userRepo), chatHandler.AssignSession) // 管理员分配会话
				staff.POST("/sessions/:id/transfer", chatHandler.TransferSession)                             // 转接会话
				staff.GET("/statistics", chatStatsHandler.GetStaffStatistics)                                 // 客服工作量统计
			}

			// 快捷回复管理
			quickReply := chat.Group("/quick-replies")
			{
				quickReply.POST("", quickReplyHandler.CreateQuickReply)       // 创建快捷回复
				quickReply.GET("", quickReplyHandler.GetQuickReplyList)       // 获取列表
				quickReply.GET("/:id", quickReplyHandler.GetQuickReply)       // 获取详情
				quickReply.PUT("/:id", quickReplyHandler.UpdateQuickReply)    // 更新
				quickReply.DELETE("/:id", quickReplyHandler.DeleteQuickReply) // 删除
			}
		}

		// 敏感词管理（仅管理员）
		sensitiveWords := api.Group("/sensitive-words", middleware.AdminAuth(userRepo))
		{
			sensitiveWords.POST("", sensitiveWordHandler.CreateSensitiveWord)         // 创建敏感词
			sensitiveWords.GET("", sensitiveWordHandler.GetSensitiveWordList)         // 获取列表
			sensitiveWords.GET("/:id", sensitiveWordHandler.GetSensitiveWord)         // 获取详情
			sensitiveWords.PUT("/:id", sensitiveWordHandler.UpdateSensitiveWord)      // 更新
			sensitiveWords.DELETE("/:id", sensitiveWordHandler.DeleteSensitiveWord)   // 删除
			sensitiveWords.POST("/reload", sensitiveWordHandler.ReloadSensitiveWords) // 重新加载缓存
		}

		// 表情管理（前端获取，所有用户）
		emojis := api.Group("/emojis", middleware.Auth())
		{
			emojis.GET("", emojiHandler.GetEmojis)        // 获取所有表情包（按分类）
			emojis.GET("/hot", emojiHandler.GetHotEmojis) // 获取热门表情

			// 表情分类管理（仅管理员）
			emojiCategories := emojis.Group("/categories", middleware.AdminAuth(userRepo))
			{
				emojiCategories.POST("", emojiHandler.CreateEmojiCategory)       // 创建分类
				emojiCategories.GET("", emojiHandler.GetEmojiCategoryList)       // 获取分类列表
				emojiCategories.GET("/:id", emojiHandler.GetEmojiCategory)       // 获取分类详情
				emojiCategories.PUT("/:id", emojiHandler.UpdateEmojiCategory)    // 更新分类
				emojiCategories.DELETE("/:id", emojiHandler.DeleteEmojiCategory) // 删除分类
			}

			// 表情管理（仅管理员）
			emojiItems := emojis.Group("/items", middleware.AdminAuth(userRepo))
			{
				emojiItems.POST("", emojiHandler.CreateEmoji)       // 创建表情
				emojiItems.GET("", emojiHandler.GetEmojiList)       // 获取表情列表
				emojiItems.GET("/:id", emojiHandler.GetEmoji)       // 获取表情详情
				emojiItems.PUT("/:id", emojiHandler.UpdateEmoji)    // 更新表情
				emojiItems.DELETE("/:id", emojiHandler.DeleteEmoji) // 删除表情
			}
		}
	}

	// 启动定时任务：自动关闭超时会话
	go func() {
		ticker := time.NewTicker(1 * time.Hour) // 每小时执行一次
		defer ticker.Stop()

		log.Println("[定时任务] 会话超时检查任务已启动，间隔：1小时")

		// 立即执行一次
		if count, err := chatService.AutoCloseInactiveSessions(24); err == nil && count > 0 {
			log.Printf("[定时任务] 首次检查：关闭了 %d 个超时会话", count)
		}

		// 定时执行
		for range ticker.C {
			if count, err := chatService.AutoCloseInactiveSessions(24); err != nil {
				log.Printf("[定时任务] 关闭超时会话失败: %v", err)
			} else if count > 0 {
				log.Printf("[定时任务] 关闭了 %d 个超过24小时无活动的会话", count)
			}
		}
	}()

	// 启动服务器
	addr := fmt.Sprintf(":%d", cfg.Server.Port)
	log.Printf("服务器启动在端口 %s", addr)
	if err := r.Run(addr); err != nil {
		log.Fatalf("服务器启动失败: %v", err)
	}
}
